using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Role;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Role
{
    public class AddRoleHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepo;
        private readonly IBaseRepository<PermissionRoleModel> _rolePermissionRepo;
        private readonly IBaseRepository<PermissionModel> _permissionRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<AddRoleHandler> _logger;

        public AddRoleHandler(
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<PermissionRoleModel> rolePermissionRepo,
            IBaseRepository<PermissionModel> permissionRepo,
            IMapper mapper,
            ILogger<AddRoleHandler> logger)
        {
            _roleRepo = roleRepo;
            _rolePermissionRepo = rolePermissionRepo;
            _permissionRepo = permissionRepo;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var validPermissionIds = new HashSet<long>(_permissionRepo.GetAll().Select(p => p.Id).ToList());
                if (request.PermissionIds.Any(pid => !validPermissionIds.Contains(pid)))
                {
                    return new ApiResult<int> { Msg = "存在无效的权限ID", Code = ApiEnum.Error };
                }
     
                var role = _mapper.Map<RoleModel>(request);
                role.Id = YitIdHelper.NextId();
                int r = await _roleRepo.CreateAsync(role);
                int r1 = 0;
                foreach (var pid in request.PermissionIds)
                {
                    r+= await _rolePermissionRepo.CreateAsync(new PermissionRoleModel {Id = YitIdHelper.NextId(), RoleId = role.Id, PermissionId = pid });
                }
                _logger.LogInformation($"新增角色{role.RoleName}成功!");
                return new ApiResult<int> { Msg = "新增角色成功!", Code = ApiEnum.Success, Data = r+r1 };
            }
            catch (Exception ex)
            {
                _logger.LogError("新增角色发生异常：" + ex.Message);
                return new ApiResult<int> { Msg = "新增角色发生异常：" + ex.Message, Code = ApiEnum.Error};
            }
        }
    }
} 